import React, {forwardRef, PropsWithChildren, useImperativeHandle, useState} from 'react';
import {Button, Modal} from "antd";
import {ModalProps} from "antd/lib/modal";

/** 模态对话框组件属性,属性[visible]被排除, [visible]由本组件接管控制*/
export interface XtraModalProps extends Omit<ModalProps, 'visible'> {
  /** 是否显示确定按钮 */
  okButtonVisible?: boolean;
  /** 确定按钮显示在前面 */
  okButtonFirst?: boolean;
  /** 确定按钮 loading */
  okButtonLoading?: boolean;
  /** 是否显示取消按钮 */
  cancelButtonVisible?: boolean;
}

/** 模态对话框组件方法 */
export interface XtraModalMethods {
  /** 显示模态对话框 */
  show: () => void;
  /** 隐藏模态对话框 */
  hide: () => void;
}

/** 扩展模态对话框组件 */
const XtraModal = forwardRef<XtraModalMethods, PropsWithChildren<XtraModalProps>>((props, ref) => {
  const {
    children, okButtonVisible, okButtonFirst, okButtonLoading, cancelButtonVisible,
    okText, okType, cancelText, okButtonProps, cancelButtonProps, ...rest
  } = props;
  const [visible, setVisible] = useState<boolean>(false);

  // 如果调用者未指定[onCancel]回调函数,则生成默认的onCancel,默认为关闭对话框
  if (rest.onCancel === undefined) {
    rest.onCancel = () => {
      setVisible(false);
    };
  }

  //暴露给父组件的对象(属性和方法)
  useImperativeHandle(ref, () => ({
    show: () => {
      setVisible(true);
    },
    hide: () => {
      setVisible(false);
    },
  }), []);

  if (visible && rest.footer === undefined) {
    // 如果调用者未指定[onOk]回调函数,则生成默认的onOk,默认为关闭对话框
    let onOk = rest.onOk;
    if (onOk === undefined) {
      onOk = () => {
        setVisible(false);
      };
    }
    const okButton = okButtonVisible ? (
      // @ts-ignore
      <Button {...okButtonProps} key="submit" type={okType} loading={okButtonLoading} onClick={onOk}>{okText}</Button>
    ) : null;

    const {onCancel} = rest;
    const cancelButton = cancelButtonVisible ? (
      <Button {...cancelButtonProps} key="cancel" onClick={onCancel}>{cancelText}</Button>
    ) : null;

    const footerArray = [];
    if (okButtonFirst) {
      if (okButton != null) footerArray.push(okButton);
      if (cancelButton != null) footerArray.push(cancelButton);
    } else {
      if (cancelButton != null) footerArray.push(cancelButton);
      if (okButton != null) footerArray.push(okButton);
    }
    rest.footer = footerArray;
  }

  return (
    <Modal visible={visible} {...rest}>
      {children}
    </Modal>
  );
});

/** 组件默认值 */
XtraModal.defaultProps = {
  destroyOnClose: true,
  okButtonVisible: true,
  okButtonFirst: false,
  okButtonLoading: false,
  cancelButtonVisible: true,
  okText: '确定',
  okType: 'primary',
  cancelText: '取消',
};

/** 缓存模态对话框组件,只有组件的props发生变化时才会重新绘制组件 */
export default React.memo(XtraModal);
